<template>
  <div class="wrap">
    <!-- <div class="title">修改当前管理员账户信息</div> -->
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="ruleForm"
      status-icon
      :rules="rules"
      label-width="auto"
      class="ruleForm-wrap"
    >
      <el-form-item label="用户名" prop="user_wanted">
        <el-input
          v-model="ruleForm.user_wanted"
          :disabled="true"
          minlength="5"
          message
          placeholder="用户名只能为英文开头至少3位,可包含数字、中划线、下划线"
          type="text"
        />
      </el-form-item>
      <el-form-item label="修改昵称" prop="nick_name">
        <el-input v-model="ruleForm.nick_name" />
      </el-form-item>
      <el-form-item label="修改密码" prop="user_pwd">
        <el-input
          v-model="ruleForm.user_pwd"
          minlength="5"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="修改邮箱" prop="email">
        <el-input v-model="ruleForm.email" minlength="5" autocomplete="off" />
      </el-form-item>
      <el-form-item label="修改手机号" prop="mobile">
        <el-input v-model.number="ruleForm.mobile" />
      </el-form-item>
      <el-form-item label="登录有效期">
        <el-select v-model="ruleForm.token_expired" placeholder="请选择">
          <el-option label="永不失效" :value="0" />
          <el-option label="10分钟" :value="10" />
          <el-option label="30分钟" :value="30" />
          <el-option label="60分钟" :value="60" />
        </el-select>
      </el-form-item>
      <el-form-item label="选择角色：">
        <el-checkbox-group v-model="ruleForm.selRole">
          <el-checkbox
            v-for="item in roleLabel"
            :value="item.role_id"
            :role_id="item.role_id"
            :key="item.role_id"
            >{{ item.role_name }}</el-checkbox
          >
        </el-checkbox-group>
      </el-form-item>
      <el-form-item class="btn-wrap">
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          修改
        </el-button>
        <el-button type="warning" plain @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted, getCurrentInstance } from 'vue'
import { ElMessage } from 'element-plus'
import { postData } from '@/http/request.js'
import { useRouter, useRoute } from 'vue-router'
let router = useRouter()
let route = useRoute()
const { proxy } = getCurrentInstance()

let ruleFormRef = ref(null)
const user_name = route.query.id
const roleLabel = ref([])

var checkPass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    // if (this.form.ruleForm.user_pwd !== "") {
    //   this.$refs[form.ruleForm].validateField("checkPass");
    // }
    callback()
  }
}
var checkEmail = (rule, value, callback) => {
  const regEmail = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/
  if (regEmail.test(value)) {
    //  console.log(regEmail.test(value));
    return callback()
  } else if (value == '') {
    return callback()
  } else {
    callback(new Error('请输入合法邮箱'))
    //callback();
  }
}
var checkPhone = (rule, value, callback) => {
  //  console.log(typeof value, "\\\\/");
  const phoneReg = /^1[3|4|5|7|8][0-9]{9}$/
  if (!Number.isInteger(+value)) {
    callback(new Error('请输入数字值'))
  } else {
    if (phoneReg.test(value)) {
      callback()
    } else if (value == '') {
      return callback()
    } else {
      callback(new Error('电话号码格式不正确'))
      // callback();
    }
  }
}

const ruleForm = reactive({
  user_wanted: user_name,
  modifyNickname: '',
  modifyPwd: '',
  modifyMobile: '',
  modifyEmail: '',
  token_expired: 30,
  selRole: [],
})

const rules = reactive({
  modifyNickname: [
    { required: false, message: '请输入新的昵称', trigger: 'blur' },
  ],
  modifyPwd: [
    {
      required: false,
      message: '请输入新的密码',
      trigger: 'change',
    },
  ],
  modifyMobile: [
    { required: false, message: '请输入手机号码', trigger: 'blur' },
    { validator: checkPhone, trigger: 'blur' },
  ],
  modifyEmail: [
    { required: false, message: '请输入邮箱', trigger: 'blur' },
    { validator: checkEmail, trigger: 'blur' },
  ],
  token_expired: [{ required: false, message: '', trigger: 'blur' }],
  selRole: [
    {
      type: 'array',
      required: false,
      message: '请至少选择一个角色',
      trigger: 'change',
    },
  ],
})

let getInit = () => {
  postData('/sys/admin/info', {
    user_wanted: user_name,
  })
    .then((res) => {
      console.log(res)
      if (res.code == 0) {
        let datas = res.datas
        Object.assign(ruleForm, datas)
        console.log(ruleForm)
        if (datas.token_expired == 0) {
          ruleForm.token_expired = '永不失效'
        } else {
          ruleForm.token_expired = datas.token_expired + '分钟'
        }
      } else if (res.code == -56055) {
        return
      } else {
        ElMessage({
          type: 'error',
          message: res.code + '，' + res.msg,
        })
      }
    })
    .catch((err) => {
      console.log(err)
      ElMessage({
        type: 'error',
        message: '请稍后重试',
      })
    })
}

let getRoleLabel = () => {
  postData('/role/list', {
    user_wanted: user_name,
  })
    .then((res) => {
      var arr = []
      if (res.code == 0) {
        let roles = res.datas.roles
        roleLabel.value = roles
        //初始的时候，根据authorized，勾选上
        for (var i = 0; i < roles.length; i++) {
          if (roles[i].authorized == 1) {
            arr.push(roles[i].role_id)
          }
        }
        // proxy.set(ruleForm, 'selRole', arr)
        Object.assign(ruleForm.selRole, { ...arr })
      } else if (res.code == -56055) {
        return
      } else {
        ElMessage({
          type: 'error',
          message: 'err',
        })
      }
    })
    .catch((res) => {
      ElMessage({
        type: 'error',
        message: 'err',
      })
    })
}

const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      postData('/sys/admin/update', {
        user_wanted: ruleForm.user_wanted,
        user_pwd: ruleForm.user_pwd,
        nick_name: ruleForm.nick_name,
        mobile: ruleForm.mobile,
        email: ruleForm.email,
        token_expired: Number(ruleForm.token_expired),
        roles: ruleForm.selRole,
      })
        .then((res) => {
          if (res.code == 0) {
            ElMessage({
              type: 'success',
              message: '修改成功',
            })
            setTimeout(() => {
              router.push('/adminList')
            }, 3000)
          } else {
            ElMessage({
              type: 'error',
              message: '修改失败',
            })
          }
        })
        .catch((err) => {
          console.log(err)
        })
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
}

onMounted(() => {
  getInit()
  getRoleLabel()
})
</script>
<style scope>
.wrap {
  margin: 20px 0 0 20px;
}

.title {
  width: 100%;
  height: 40px;
  line-height: 40px;
  position: relative;
  /* background: #c0dee2; */
  padding-left: 30px;
  font-size: 14px;
  margin: 6px 0 20px 0;
  /* border-radius: 12px 12px 0 0; */
  /* font-weight: bold; */
}

.title::before {
  content: '';
  width: 2px;
  height: 16px;
  background: #676a6d;
  position: absolute;
  top: 12px;
  left: 15px;
}

.title span {
  float: left;
  color: #676a6d;
  margin-left: 25px;
}

.btn-wrap {
  margin-top: 30px;
}
</style>
